import { Input, Modal, Form, FormItem, Button } from "view-ui-plus";
import { defineComponent, ref, reactive, nextTick } from "vue";
import type { PropType } from "vue";

interface textProps {
  title: string;
  label?: string;
}

export default defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      dafault: false,
    },
    showText: {
      type: Object as PropType<textProps>,
      default: () => null,
    },
    callback: {
      type: Function as PropType<(...res: any) => Promise<any>>,
      default: () => {},
    },
    okText: {
      type: String,
      default: "确定",
    },
    cancelText: {
      type: String,
      default: "取消",
    },
  },
  emits: ["update:modelValue", "confirm"],
  setup(props, { emit, slots }) {
    const loading = ref(true);

    const form = ref(null);

    const formValidate = reactive({
      value: "",
    });

    const ruleValidate = reactive({
      value: [
        {
          required: true,
          message: `${props.showText.label || props.showText.title}是必填项`,
          trigger: "change",
        },
      ],
    });

    const onOk = () => {
      form.value.validate((valid) => {
        if (valid) {
          props
            .callback(formValidate)
            .then(() => {
              onUpdate();
            })
            .catch(() => {
              stopClose();
            });
        } else {
          stopClose();
        }
      });
    };

    const stopClose = () => {
      loading.value = false;
      nextTick(() => {
        loading.value = true;
      });
    };

    const onUpdate = () => {
      form.value.resetFields();
      emit("update:modelValue", false);
      emit("confirm");
    };

    const onCancel = () => {
      form.value.resetFields();
      emit("update:modelValue", false);
    };

    return () => (
      <Modal
        title={props.showText.title}
        model-value={props.modelValue}
        onOnOk={onOk}
        onOnCancel={onCancel}
        loading={loading.value}
        ok-text={props.okText}
        cancel-text={props.cancelText}
        footer-hide={!!slots.footer}
      >
        <>
          <Form ref={form} model={formValidate} rules={ruleValidate}>
            <FormItem label={props.showText.label} prop="value">
              <Input
                v-model={formValidate.value}
                type="textarea"
                maxlength={150}
                placeholder="请输入,最多150字"
                autosize={{ minRows: 6 }}
              />
            </FormItem>
          </Form>
          {slots.footer &&
            slots.footer({ formValidate, form, stopClose, onUpdate })}
        </>
      </Modal>
    );
  },
});
